/*
 * Filename:    WarnPoolServiceImpl.java
 * Copyright:   2014 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2014年11月3日
 */
package com.paic.mhis.hcpms.warning.biz.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.paic.mhis.hcpms.quota.calculationreport.calculationdataItem.dto.CalculationResultDTO;
import com.paic.mhis.hcpms.quota.calculationreport.calculationkpi.common.util.ContentFinalUtil;
import com.paic.mhis.hcpms.quota.settlement.common.Constants;
import com.paic.mhis.hcpms.warning.biz.service.WarningPoolService;
import com.paic.mhis.hcpms.warning.dao.WarningPoolDAO;
import com.paic.mhis.hcpms.warning.dto.WarningIndicationDTO;
import com.paic.mhis.hcpms.warning.dto.WarningParameterJobDTO;
import com.paic.mhis.hcpms.warning.dto.WarningPoolDTO;
import com.paic.mhis.hcpms.warning.dto.WarningValueDescDTO;

@Service("warningPoolService")
public class WarningPoolServiceImpl implements WarningPoolService {
	@Autowired
	private WarningPoolDAO warningPoolDAO;

	@Override
	public void insertWarnPoolData(WarningParameterJobDTO warningParameter) {
		// TODO Auto-generated method stub
		CalculationResultDTO resultDto = new CalculationResultDTO();
		try {
			List<WarningPoolDTO> warnPoolList = getWarnPoolData(warningParameter);
			warningPoolDAO.insertWarnPoolData(warnPoolList);
			resultDto.setIsError("N");
			resultDto.setMessage("预警事件池完成！");
		} catch (Exception e) {
			resultDto.setIsError("Y");
			resultDto.setMessage("预警事件池发生错误！" + e.getCause().getCause().getMessage());
		}

	}

	public List<WarningPoolDTO> getWarnPoolData(WarningParameterJobDTO warningParameter) {
		// TODO Auto-generated method stub
		List<WarningPoolDTO> resultList = new ArrayList<WarningPoolDTO>();
		List<WarningIndicationDTO> indicationList = warningPoolDAO.getWarnIndicationData(warningParameter);
		List<WarningValueDescDTO> warnValueDescList = warningPoolDAO.getWarnValueDescData(warningParameter);
		BigDecimal kpiValue;
		// 2015-03-04阈值改为范围修改
		String operatorDesc = "";
		for (WarningValueDescDTO valueDescDTO : warnValueDescList) {
			for (WarningIndicationDTO indicationDTO : indicationList) {
				if (valueDescDTO.getKpiCode().equals(indicationDTO.getKpiCode())
						&& valueDescDTO.getSociationCode().equals(indicationDTO.getSociationCode())) {
					kpiValue = getKpiValue(valueDescDTO.getValueType(), indicationDTO);
					// 2015-03-04阈值改为范围修改
					// if (isWarnPool(kpiValue, valueDescDTO.getWarnValue(),
					// valueDescDTO.getOperator())) {
					if (isWarnPool2(kpiValue, valueDescDTO.getUpperLimit(), valueDescDTO.getLowerLimit(), operatorDesc) != 0) {
						WarningPoolDTO poolDTO = new WarningPoolDTO();
						poolDTO.setRegionCode(warningParameter.getRegionCode());
						poolDTO.setKpiNo(indicationDTO.getKpiCode());
						poolDTO.setValueCode(valueDescDTO.getValueCode());
						poolDTO.setPeriod(indicationDTO.getPeriod());
						poolDTO.setKpiTime(indicationDTO.getKpiTime());
						// poolDTO.setReasonDesc(valueDescDTO.getResonDesc());
						poolDTO.setReasonDesc(replaceResonDesc(valueDescDTO.getResonDesc(), valueDescDTO,
								indicationDTO.getKpiTime(), kpiValue, valueDescDTO.getValueType(),
								indicationDTO.getVisitType(), valueDescDTO.getKpiUnit(), operatorDesc));
						poolDTO.setKpiValue(kpiValue);
						// 2015-03-04阈值改为范围修改
						// poolDTO.setWarnValue(valueDescDTO.getWarnValue());
						poolDTO.setOrgCode(indicationDTO.getOrgCode());
						poolDTO.setVisitType(indicationDTO.getVisitType());
						resultList.add(poolDTO);
					} else {
						continue;
					}
				} else {
					continue;
				}
			}
		}
		return resultList;
	}

	public String replaceResonDesc(String resonDesc, WarningValueDescDTO valueDescDTO, String kpiTime,
			BigDecimal kpiValue, String valueType, String visitType, String kpiUnit, String operatorDesc) {
		String valueName = "";
		if (valueType.equals("01")) {// 同比
			valueName = "同比";
		} else if (valueType.equals("02")) {// 环比
			valueName = "环比";
		} else {// 增量
			valueName = "增量";
		}
		String typeName = "";
		if (null != visitType) {
			if (Constants.visitType_hosp_value.equals(visitType)) {
				typeName = "住院";
			}
			if (Constants.visitType_out_value.equals(visitType)) {
				typeName = "门诊";
			}
		}
		String result = resonDesc.replace("<KPI_MONTH>", kpiTime)
				.replace("<KPI_NAME>", typeName + valueDescDTO.getKpiName())
				.replace("<VALUE_TYPE>", valueName + "为" + kpiValue.toString() + "%，")
				// 2015-03-04阈值改为范围修改
				// .replace("<UP_DOWN>", valueDescDTO.getOperatorDesc())
				.replace("<UP_DOWN>", operatorDesc)
				// 2015-03-04阈值改为范围修改
				// .replace("<VALUE>", valueDescDTO.getWarnValue().toString());
				.replace("<VALUE>", "[" + valueDescDTO.getLowerLimit() + "-" + valueDescDTO.getUpperLimit() + "]");
		if (valueType.equals("03") && kpiUnit != null && !kpiUnit.equals("%"))
			return result.replace("%", "");
		return result;
	}

	/**
	 * 取得指标数据kpi值
	 * 
	 * @param valueType
	 * @param indicationDTO
	 * @return
	 */
	public BigDecimal getKpiValue(String valueType, WarningIndicationDTO indicationDTO) {
		if (valueType.equals("01")) {// 同比
			return indicationDTO.getPeriodRatio();
		} else if (valueType.equals("02")) {// 环比
			return indicationDTO.getChainRatio();
		} else {// 增量
			return indicationDTO.getIncremental();
		}
	}

	/**
	 * 根据操作符判断是否在预警阀值范围内
	 * 
	 * @param kpiValue
	 * @param valueDescDTO
	 * @return
	 */
	public boolean isWarnPool(BigDecimal kpiValue, BigDecimal valueDesc, String operator) {
		boolean flag = false;
		if (null == kpiValue) {
			flag = false;
		} else {
			if ((operator.equals(ContentFinalUtil.OPERATOR_EQUIAL) && kpiValue.compareTo(valueDesc) == 0)
					|| (operator.equals(ContentFinalUtil.GREATER_THAN) && kpiValue.compareTo(valueDesc) >= 0)
					|| (operator.equals(ContentFinalUtil.LESS_EQUAL) && kpiValue.compareTo(valueDesc) <= 0)
					|| (operator.equals(ContentFinalUtil.MATH_GREATER) && kpiValue.compareTo(valueDesc) > 0)
					|| (operator.equals(ContentFinalUtil.MATH_LESS) && kpiValue.compareTo(valueDesc) < 0)) {
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * 根据数值是否在预警阈值范围内
	 * 
	 * @param kpiValue
	 * @param upperValue
	 *            上限
	 * @param limitValue
	 *            下限
	 * @return
	 */
	public int isWarnPool2(BigDecimal kpiValue, BigDecimal upperValue, BigDecimal limitValue, String operatorDesc) {
		int result = 0;
		if (null == kpiValue) {
			return result;
		} else {
			if (kpiValue.compareTo(upperValue) > 0) {
				operatorDesc = ContentFinalUtil.MATH_GREATER_DESC;
				return 1;
			}
			if (kpiValue.compareTo(limitValue) < 0) {
				operatorDesc = ContentFinalUtil.MATH_LESS_DESC;
				return -1;
			}
		}
		return result;
	}

}
